package com.tyq.auth.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tyq.auth.common.ResultData;
import com.tyq.auth.security.exception.NonUserException;
import com.tyq.auth.security.exception.UserNameException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录失败处理器
 *
 * @author 谭永强
 * @date 2024-05-20
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 当身份验证尝试失败时调用。
     *
     * @param request  进行身份验证尝试的请求
     * @param response 响应
     * @param e        为拒绝身份验证请求而引发的异常
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        //此处为登录失败的处理逻辑
        ResultData<Authentication> resultData = new ResultData<>();
        if (e.getCause() instanceof NonUserException) {
            resultData.setMessage("用户不能为空!");
        } else if (e.getCause() instanceof UserNameException) {
            resultData.setMessage("用户名不存在!");
        } else if (e instanceof BadCredentialsException) {
            resultData.setMessage("密码错误!");
        } else {
            resultData.setMessage("其他异常!");
        }
        objectMapper.writeValue(response.getWriter(), resultData);
    }
}
